//
//  BabyAnimationController.m
//  HappyBaby
//
//  Created by 华哥 on 15/11/23.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "BabyAnimationController.h"
#import "FirstCell.h"
#import "BACollectionViewCell.h"
#import "BACollectionReusableView.h"
#import "FirstModel.h"
#import "Define.h"
#import "TwoModel.h"
#import "ThreeModel.h"
#import "BabyPlayerViewController.h"
#import "AnimationViewController.h"
#import "MoreCollectionViewController.h"
#import "BabyPlayerViewController.h"
#import "AnimationViewController.h"
#import "NetWorkState.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#define KUrl @"http://shaoer.qupeiyin.com/home/index"
@interface BabyAnimationController ()<UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,FirstModeldelegate>
@property(nonatomic,retain)UICollectionView *collectionView;
@property(nonatomic,retain)NSMutableArray *array;
@property(nonatomic, retain) NSMutableArray *iconArray;
@property(nonatomic, strong)NSMutableArray *everyArray;
@property(nonatomic,strong)FirstCell *cell;
@property(nonatomic,strong)BACollectionReusableView *resuableView;
@property (nonatomic,retain)MBProgressHUD *hud;

@property(nonatomic,retain)UIRefreshControl *refreshControl;
@end

static NSString *cellIdentifier = @"cell";
static NSString *firstCellIdentifier = @"firstCell";
@implementation BabyAnimationController

- (NSMutableArray *)array
{
    if (!_array)
    {
        _array = [NSMutableArray array];
    }
    
    return _array;
}
- (NSMutableArray *)iconArray
{
    if (!_iconArray)
    {
        _iconArray = [NSMutableArray array];
    }
    return _iconArray;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.translucent = NO;
    
    //判断网络状态；
    if (![[NetWorkState shareInstance]reachAbility])
    {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"网络状态不佳", nil];
        return [alertView show];

    }
    [self setProgressHud];
    
    UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    titleLabel.font = [UIFont fontWithName:@"BodoniSvtyTwoITCTT-Book" size:17];
    titleLabel.text = @"少儿趣配音";
    titleLabel.textAlignment = NSTextAlignmentLeft;
    UIBarButtonItem *leftBar = [[UIBarButtonItem alloc]initWithCustomView:titleLabel];
    self.navigationItem.leftBarButtonItem = leftBar;
    
   //创建一个layout
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) collectionViewLayout:layout];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    //注册表头
    [self.collectionView registerClass:[BACollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    
    //自定义注册cell
    [self.collectionView registerClass:[FirstCell class] forCellWithReuseIdentifier:firstCellIdentifier];
    
    //自定义注册cell
    [self.collectionView registerClass:[BACollectionViewCell class] forCellWithReuseIdentifier:cellIdentifier];
    [self.view addSubview:self.collectionView];
    
    //数据解析；
    [self sessionDataWithUrl:KUrl];
    //上拉加载更多
    [self.collectionView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    [self.collectionView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    
}

//解析数据
- (void)sessionDataWithUrl:(NSString *)url
{
    
    [[[NSURLSession sharedSession]dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *array = [dic objectForKey:@"data"];
        for (int i = 0; i < array.count; i++)
        {
            if (i == 0)
            {
                self.everyArray = [NSMutableArray array];
                NSDictionary *smallDic = array[0];
                NSArray *sliderArray = [smallDic objectForKey:@"slider"];
                for (NSDictionary *slider in sliderArray)
                {
                    FirstModel *model = [[FirstModel alloc]init];
                    [model setValuesForKeysWithDictionary:slider];
                    [_everyArray addObject:model];
                }
                [self.array addObject:_everyArray];
            }
            
            if (i == 1 || i == 4 || i == 5)
            {
                TwoModel *model = [[TwoModel alloc]init];
                NSDictionary *dic = array[i];
                [model setValuesForKeysWithDictionary:dic];
                NSMutableArray *courseArray = [NSMutableArray array];
                for (NSDictionary *courseDic in model.course)
                {
                    ThreeModel *model = [[ThreeModel alloc]init];
                    [model setValuesForKeysWithDictionary:courseDic];
                    [courseArray addObject:model];
                }
                [self.iconArray addObject:model];
                [self.array addObject:courseArray];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.collectionView reloadData];
            
        });
    }]resume];
    
}
//上拉加载
- (void)footerRefresh
{
    [self.collectionView reloadData];
    [self.collectionView.footer endRefreshing];
    
}

//下拉刷新；
- (void)headerRefresh
{

    [self.collectionView.header endRefreshing];
    
}

//菊花；
- (void)setProgressHud
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    _hud.frame = self.view.bounds;
    self.hud.backgroundColor = [UIColor redColor];
    _hud.minSize = CGSizeMake(100, 100);
    //菊花的状态；
    _hud.mode = MBProgressHUDModeIndeterminate;
    [self.view addSubview:_hud];
    [_hud show:YES];
    
}


//每个分区返回多少个Item
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.array.count == 0)
    {
        return 0;
    }
    else
    {
        if (section == 0)
        {
            return 1;
        }
        return 4;
    }
}

//返回多少个分区；
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (self.iconArray.count == 0)
    {
        return 0;
    }
    else
    {
        return self.array.count;
    }
}

//返回cell的执行方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        FirstCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:firstCellIdentifier forIndexPath:indexPath];

//        self.cell.titleArray = titleArray;
        cell.array = _everyArray;
        //设置代理；
        cell.delegate = self;
        
        
        return cell;
    }
    
    else
    {
        BACollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
        //cell.backgroundColor = [UIColor yellowColor];
        
        NSArray *array = self.array[indexPath.section];
        ThreeModel *model = array[indexPath.row];
        cell.model = model;
        
        return cell;
 
    }
}

//点击cell的执行方法；
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section != 0)
    {
        BabyPlayerViewController *playerVc = [[BabyPlayerViewController alloc]init];
        NSArray *array = self.array[indexPath.section];
        ThreeModel *model = array[indexPath.row];
        NSString *string = [NSString stringWithFormat:@"http://shaoer.qupeiyin.com/course/detail_new?course_id=%@",model.myId];
        playerVc.url = string;

        [self.navigationController pushViewController:playerVc animated:YES];
        
    }
    
}

//返回每个item的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        CGFloat height = 340*kScreenWidth/640;
        return CGSizeMake(kScreenWidth, height);
    }
    else
    {
        
        CGFloat width = (kScreenWidth - 15)/2;
        CGFloat height = 340*width/680;
        return CGSizeMake(width, height + 15);
        
    }
    
    
}

//上 左 下 右 针对于集合视图整体来说的；（也就是相对于每个分区来说的）
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0)
    {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }
    else
    {
        return UIEdgeInsetsMake(0, 5, 0, 5);
        
    }
    
}

//返回行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    if (section == 0)
    {
        return 0;
    }
    else
    {
        return 5;
        
    }
    
}

//返回列间距；
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    
    if (section == 0)
    {
        return 0;
    }
    else
    {
        return 5;
    }
    
}

//返回表头的大小；
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(nonnull UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0)
    {
        return CGSizeMake(0, 0);
    }
    else
    {
        return CGSizeMake(kScreenWidth, 40);
        
    }
    
}

//返回表头
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return nil;
    }
    else
    {
        
      BACollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];        
        //headerView.backgroundColor = [UIColor grayColor];
        TwoModel *model = self.iconArray[indexPath.section - 1];
        headerView.model = model;
        self.resuableView = headerView;
        if (indexPath.section == 1)
        {
            self.resuableView.moreBtn.tag = 1;
        }
        else
        {
            self.resuableView.moreBtn.tag = indexPath.section + 1;
        }
        
        
        [self.resuableView.moreBtn addTarget:self action:@selector(moreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        return self.resuableView;
        
    }
}


//moreBtn按钮执行方法
- (void)moreBtnAction:(UIButton *)btn
{
    NSString *URL = [NSString stringWithFormat:@"http://shaoer.qupeiyin.com/course/get_course_list?start=0&rows=20&category_id=%ld&level=all&sort=new&ishow=0",(long)btn.tag];
    MoreCollectionViewController *moreCollectionVc = [[MoreCollectionViewController alloc]init];
    moreCollectionVc.url = URL;
    [self.navigationController pushViewController:moreCollectionVc animated:YES];
    
}


//执行代理方法
- (void)skipWithModel:(FirstModel *)model
{
    if ([model.title isEqualToString:@"精彩活动"])
    {
        AnimationViewController *animationVc = [[AnimationViewController alloc]init];
        animationVc.model = model;
        [self.navigationController pushViewController:animationVc animated:YES];
    }
    else
    {
        BabyPlayerViewController *playerController = [[BabyPlayerViewController alloc]init];
        playerController.firModel = model;
        NSString *string = [NSString stringWithFormat:@"http://shaoer.qupeiyin.com/course/detail_new?course_id=%@",model.myId];
        playerController.topUrl = string;
       [self.navigationController pushViewController:playerController animated:YES];
 
    }
}




@end
